import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:qunaimedical/im/chat/chat_page.dart';
import 'package:qunaimedical/im/common_widgets.dart';
import 'package:qunaimedical/im/item_conversation.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/auth_util.dart';
import 'package:qunaimedical/utils/dialog_util.dart';
import 'package:qunaimedical/utils/event_bus_manager.dart';
import 'package:qunaimedical/utils/log_util.dart';
import 'package:qunaimedical/values/urls.dart';

class ConversationsPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => ConversationsPageState();
}

class ConversationsPageState extends State<ConversationsPage> {
  final String _tag = 'ConversationsPageState';

  List<EMConversation> _conversationsList = [];

  @override
  void initState() {
    super.initState();
    // 添加环信回调监听
    _addChatListener();
    _loadAllConversations();
  }

  void dispose() {
    // 移除环信回调监听
    EMClient.getInstance.chatManager.removeEventHandler(_tag);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('消息'),
        leading: Container(),
      ),
      body: ListView.separated(
        itemBuilder: ((context, index) => conversationWidgetForIndex(index)),
        separatorBuilder: ((context, index) => Divider()),
        itemCount: _conversationsList.length,
      ),
    );
  }

  /// 加载会话列表
  void _loadAllConversations() async {
    if (!AuthUtil.isLogin()) {
      return;
    }
    try {
      List<EMConversation> fixedConvs = await _genarateFixedConversations();
      List<EMConversation> list =
          await EMClient.getInstance.chatManager.loadAllConversations();
      var toRemove = [];
      for (var contact in _contacts) {
        for (var conv in list) {
          if (conv.id.toLowerCase() == contact["id"]!.toLowerCase()) {
            toRemove.add(conv);
          }
        }
      }
      list.removeWhere((element) => toRemove.contains(element));
      _conversationsList.clear();
      _conversationsList.addAll(fixedConvs);
      _conversationsList.addAll(list);
    } catch (e) {
      Log.d(_tag, e);
    } finally {
      setState(() {});
    }
  }

  /// 获取会话列表widget
  Widget conversationWidgetForIndex(int index) {
    return slidableItem(
      child: FutureBuilder(
        builder: (BuildContext context,
            AsyncSnapshot<ItemConversationProps> snapshot) {
          ItemConversationProps props = ItemConversationProps(
              name: "", lastMsg: "", time: "", unreadCount: 0);
          if (snapshot.hasData) {
            props.name = snapshot.data!.name;
            props.lastMsg = snapshot.data!.lastMsg;
            props.time = snapshot.data!.time;
            props.unreadCount = snapshot.data!.unreadCount;
          }
          return ItemConversation(
            props: props,
            onTap: () => _conversationItemOnPress(index),
          );
        },
        future: _getConversationProps(index),
      ),
      // 侧滑事件，有必要可以加上置顶之类的
      actions: [
        slidableDeleteAction(onTap: () {
          DialogUtil.showAlertDialog(
            context,
            "确定删除该条消息？",
            onPressed: () => _deleteConversation(index),
          );
        })
      ],
    );
  }

  Future<ItemConversationProps> _getConversationProps(int index) async {
    var conv = _conversationsList[index];
    String _latestMessageInfo = "";
    String _serverTime = "";
    EMMessage? _latestMessage = await conv.latestMessage();
    if (_latestMessage != null) {
      _serverTime = timeStrByMs(_latestMessage.serverTime);
      switch (_latestMessage.body.type) {
        case MessageType.TXT:
          var body = _latestMessage.body as EMTextMessageBody;
          _latestMessageInfo = body.content;
          break;
        case MessageType.IMAGE:
          _latestMessageInfo = '[图片]';
          break;
        case MessageType.VIDEO:
          _latestMessageInfo = '[视频]';
          break;
        case MessageType.FILE:
          _latestMessageInfo = '[文件]';
          break;
        case MessageType.VOICE:
          _latestMessageInfo = '[语音]';
          break;
        case MessageType.LOCATION:
          _latestMessageInfo = '[位置]';
          break;
        default:
          _latestMessageInfo = '';
      }
    }
    String _name = conv.ext?["name"] ?? "";
    if (index > 4) {
      try {
        String url = "${Urls.USER_INFO}${conv.id}";
        Response response = await XHttp.instance.get(url);
        if (mounted) {
          if (response.statusCode == 200 && response.data != null) {
            _name = response.data["data"]["name"];
            conv.setExt({"name": _name});
          }
        }
      } on DioError catch (e) {
        Log.d(_tag, e);
      }
    }
    int _unreadCount = await conv.unreadCount();
    return ItemConversationProps(
      name: _name,
      lastMsg: _latestMessageInfo,
      time: _serverTime,
      unreadCount: _unreadCount,
    );
  }

  /// 侧滑删除按钮点击
  _deleteConversation(int index) async {
    try {
      await EMClient.getInstance.chatManager
          .deleteConversation(_conversationsList[index].id);
      _conversationsList.removeAt(index);
    } on Error {
    } finally {
      setState(() {});
    }
  }

  /// 会话被点击
  _conversationItemOnPress(int index) async {
    EMConversation con = _conversationsList[index];
    Navigator.push(context, MaterialPageRoute(builder: (c) => ChatPage(con)))
        .then((value) {
      // 返回时刷新页面
      _loadAllConversations();
      // 通知更新首页底部的未读标记
      eventBus.fire(EventBusMessage.updateUnreadMsgFlag);
    });
  }

  void _addChatListener() {
    EMClient.getInstance.chatManager.addEventHandler(
      _tag,
      EMChatEventHandler(
        onMessagesReceived: (messages) {
          _loadAllConversations();
        },
      ),
    );
  }

  /// 固定的几个对话
  Future<List<EMConversation>> _genarateFixedConversations() async {
    List<EMConversation> list = [];
    for (var i = 0; i < _contacts.length; i++) {
      EMConversation? conv = await EMClient.getInstance.chatManager
          .getConversation(_contacts[i]["id"]!);
      conv?.setExt(_contacts[i]);
      list.add(conv!);
    }
    return list;
  }
}

const _contacts = [
  {
    "id": "10001",
    "name": "系统消息",
  },
  {
    "id": "10002",
    "name": "客服小群",
  },
  {
    "id": "10003",
    "name": "客服小爱",
  },
  {
    "id": "10004",
    "name": "ChatQA",
  },
  {
    "id": "10005",
    "name": "问题反馈",
  },
];
